const app = getApp();
import { baseUrl } from "../../../api/request"
import { dynamiComment, dynamiCommentOption, dynamiCollection_option, dynamiGive_option, dynamicsDetails, getDyLandscapes } from "../../../api/homePage"
import { followUser_opt } from "../../../api/my"
import { getStorage, setStorage } from "../../../utils/localStorage"
import { getMapDistance } from "../../../utils/address"
Page({
  data: {
    navData: {
      level: 2,
      title: "动态详情"
    },
    swiper: {
      autoplay: true, //自动切换
      dots: true, //指示点
      dotsColor: "#ffffff", //指示点颜色
      dotsActiveColor: "#4646A0", //选中指示点颜色
      circular: true, //衔接滑动
      duration: 3000, //滑动动画时长
      boxFlag: false,
    },
    imgUrl: baseUrl,
    soFlag: false,
    detailObj: {},
    commentList: [],
    content: "",
    navMargin: app.globalData.navHeight + app.globalData.navTop,
    sceicsList: [], //景区列表
    latlng: {},
    dynamicType: null,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    //判断用户是否已经登录，否则跳转到登录页重新登录
    // if (!getStorage("user")) {
    //     wx.redirectTo({
    //         url: '/pages/bootPage/index',
    //     });
    // };
    // /* 获取是否是从分享页进来的参数 true时 false不是 */
    // app.globalData.sheetFlag = false;
    // if (options.sheet) {
    //     app.globalData.sheetFlag = options.sheet;
    // };
    if (app.loginState()) return;
    //重置全局关于动态操作的全局变量
    app.globalData.dynamicId = null; //动态id
    app.globalData.dynamicGive = null; //动态点赞状态
    app.globalData.dynamicGiveNum = null; //动态数量
    app.globalData.dynamicCtion = null; //动态收藏状态
    app.globalData.dynamicCtionNum = null; //动态收藏数量
    app.globalData.dynamicMent = null; //动态评论数量

    let id = options.id;
    this.setData({
      user: getStorage("user"),
      latlng: getStorage("latLng"),
      dynamicType: options.dynamicType || "暂无",
    });
    app.globalData.detailPageType = this.data.dynamicType;  //详情页类型
    this.getInfo(id);
  },
  //获取用户动态详情
  getInfo(id) {
    dynamicsDetails({ userId: this.data.user.id, dynamicsId: id }).then(res => {
      res.data.data.imageScale = res.data.data.imageScale.split(",");
      this.setData({
        detailObj: res.data.data
      });
      console.log(this.data.detailObj, '动态详情');
      this.getComment_list();
      this.getScenicspotList(this.data.detailObj.id);
    });
  },
  //获取景区列表
  getScenicspotList(id) {
    let that = this.data;
    getDyLandscapes({ dynamicsId: id }).then(res => {
      if (!res.data.data || res.data.data.length === 0) {
        this.setData({
          sceicsList: []
        });
      } else {
        res.data.data.forEach(item => {
          item.imageScale = item.imageScale.split(",");
          item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
        });
        this.setData({
          sceicsList: res.data.data
        });
      };
    });
  },
  //获取当前动态评论列表
  async getComment_list() {
    const _this = this.data;
    let res = await dynamiComment({ userId: this.data.user.id, dynamicsId: _this.detailObj.id });
    const { code, data } = res.data;
    if (code === 200) {
      this.setData({
        commentList: data
      });
      //评论数量
      app.globalData.dynamicId = _this.detailObj.id;
      app.globalData.dynamicMent = this.data.commentList.length;
      //动态点赞和收藏
      app.globalData.dynamicGive = _this.detailObj.likeState ? 1 : 2; //动态点赞状态
      app.globalData.dynamicGiveNum = _this.detailObj.likeNumber; //动态数量
      app.globalData.dynamicCtion = _this.detailObj.collectionState ? 1 : 2; //动态收藏状态
      app.globalData.dynamicCtionNum = _this.detailObj.collectionNumber; //动态收藏数量
    };
  },
  //评论用户头像点击事件
  userClick(e) {
    const item = e.currentTarget.dataset.item;
    item.id = item.userId;
    console.log(item, 'item');
    if (item.userId === this.data.user.id) {
      wx.redirectTo({
        url: '/pages/index/index?index=' + 5,
      });
    } else {
      wx.navigateTo({
        url: '/pagesWoDe/pages/personalHomepage/index?item=' + encodeURIComponent(JSON.stringify(item)),
      });
    };

  },
  //关注按钮事件
  followOpt(e) {
    let item = e.currentTarget.dataset.item,
      state = item.actionState ? false : true;
    if (state) {
      this.getFollow(item.userId, state);

    } else {
      wx.showModal({
        title: '用户关注',
        content: '请确定是否要取消对该用户的关注',
        complete: (res) => {
          if (res.confirm) {
            this.getFollow(item.userId, state);
          };
        }
      });
    };

  },
  //关注操作请求
  getFollow(id, state) {
    followUser_opt({ id: this.data.user.id, userId: id, state: state }).then(res => {
      if (res.data.code === 200) {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 1000,
        });
        this.setData({
          "detailObj.actionState": state
        });
      };
    });
  },
  //用户动态点赞或取消点赞事件
  commentClick(e) {
    let that = this.data,
      item = e.currentTarget.dataset.item,
      flag = !item.likeState ? true : false;
    dynamiGive_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
      let state = "detailObj.likeState";
      let num = "detailObj.likeNumber";
      if (res.data.code === 200) {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 1000,
        })
        app.globalData.dynamicId = item.id;
        app.globalData.dynamicGive = flag ? 1 : 2; // 1是已点赞：2是取消点赞  
        app.globalData.dynamicGiveNum = !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1;
        //初始化动态收藏状态
        app.globalData.dynamicCtion = item.collectionState ? 1 : 2; // 1是已收藏：2未收藏 
        app.globalData.dynamicCtionNum = item.collectionNumber
        this.setData({
          [state]: flag,
          [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
        });
      };
    });
  },
  //收藏或取消收藏事件
  collectionClick(e) {
    let that = this.data;
    let item = e.currentTarget.dataset.item,
      flag = !item.collectionState ? true : false;
    dynamiCollection_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
      let state = "detailObj.collectionState",
        num = "detailObj.collectionNumber";
      if (res.data.code === 200) {
        wx.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 1000,
        })
        app.globalData.dynamicId = item.id;
        app.globalData.dynamicCtion = flag ? 1 : 2; // 1是已点赞：2是取消点赞 
        app.globalData.dynamicCtionNum = flag ? item.collectionNumber + 1 : item.collectionNumber - 1
        //动态点赞初始化
        app.globalData.dynamicGive = item.likeState ? 1 : 2; // 1是已点赞：2是取消点赞  
        app.globalData.dynamicGiveNum = item.likeNumber;
        this.setData({
          [state]: flag,
          [num]: flag ? item.collectionNumber + 1 : item.collectionNumber - 1
        });
      };
    });
  },
  //评论内容bindinput事件
  pinl(e) {
    const value = e.detail.value;
    this.setData({
      content: value,
    });
  },
  //提交按钮事件
  async submit() {
    const _this = this.data;
    if (!_this.content) {
      wx.showToast({
        icon: "none",
        title: '请先输入评论内容',
      });
    } else {
      let res = await dynamiCommentOption({ userId: _this.user.id, dynamicsId: _this.detailObj.id, content: _this.content });
      wx.showToast({
        icon: 'none',
        title: res.data.msg,
        duration: 1000,
      });
      this.getComment_list();
      this.setData({
        content: "",
      });
    };
  },
  //景区列表点击事件
  relevant(e) {
    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/pagesShouYe/pages/jingquDetail/index?id=' + item.id + '&type=' + '景区',
    });
  },
  //地址图标点击事件
  addressTap(e) {
    let item = e.currentTarget.dataset.item;
    wx.openLocation({
      latitude: Number(item.latitude),
      longitude: Number(item.longitude),
    });
  },
  //返回上一页
  back() {
    if (app.globalData.sheetFlag) {
      wx.redirectTo({
        url: '/pages/index/index',
      });
    } else {
      app.globalData.detailPageType = this.data.dynamicType; //全局参数
      wx.navigateBack({
        delta: 1  // 返回上一级页面。
      });
    };
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {
    let that = this;
    return {
      title: that.data.detailObj.landscapesName,
      // imageUrl: that.data.detailObj[0],
      path: "pagesShouYe/pages/listDetail/index?id=" + that.data.detailObj.id + "&sheet=" + true,
      success: function (res) {
        console.log(res, "转发成功")
      },
      fail: function (res) {
        console.log(res, "转发失败")
      }
    }
  },
})